const express = require('express');
const axios = require('axios');
const cheerio = require('cheerio');
const router = express.Router();
const BASE_URL = 'https://www.djks5.com';

// 搜索接口
router.get('/search', async (req, res) => {
    try {
        const { key } = req.query;
        if (!key) {
            return res.status(400).json({ error: 'Search key is required' });
        }

        const response = await axios.post(`${BASE_URL}/search/`, `type=articlename&searchkey=${key}`, {
            headers: {
                'User-Agent': 'Mozilla/5.0 (Linux; Android 9) Mobile Safari/537.36',
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        });

        const $ = cheerio.load(response.data);
        const books = [];

        $('.txt-list li:not(.qu-2lmu-qd5o-lvij)').each((index, element) => {
            const book = {
                name: $(element).find('.s2').text().trim(),
                author: $(element).find('.s4').text().trim(),
                kind: $(element).find('.s1').text().trim() + ' ' + $(element).find('.s5').text().trim().replace(/\[|\]/g, ''),
                lastChapter: $(element).find('.s3').text().trim(),
                url: BASE_URL + $(element).find('a').attr('href')
            };
            books.push(book);
        });

        res.json(books);
    } catch (error) {
        console.error('Search error:', error);
        res.status(500).json({ error: 'Internal server error' });
    }
});

// 获取书籍详情
router.get('/book', async (req, res) => {
    try {
        const { url } = req.query;
        if (!url) {
            return res.status(400).json({ error: 'Book URL is required' });
        }

        const response = await axios.get(url, {
            headers: {
                'User-Agent': 'Mozilla/5.0 (Linux; Android 9) Mobile Safari/537.36'
            }
        });

        const $ = cheerio.load(response.data);
        
        const bookInfo = {
            name: $('[property$=book_name]').attr('content'),
            author: $('[property$=author]').attr('content'),
            kind: $('[property~=category|status]').attr('content'),
            lastChapter: $('[property$=lastest_chapter_name]').attr('content'),
            updateTime: $('[property$=update_time]').attr('content'),
            coverUrl: $('.imgbox img').attr('src'),
            intro: $('[property$=description]').attr('content')
        };

        res.json(bookInfo);
    } catch (error) {
        console.error('Book info error:', error);
        res.status(500).json({ error: 'Internal server error' });
    }
});

// 获取目录
router.get('/toc', async (req, res) => {
    try {
        const { url } = req.query;
        if (!url) {
            return res.status(400).json({ error: 'Book URL is required' });
        }

        // 获取所有分页
        const response = await axios.get(url, {
            headers: {
                'User-Agent': 'Mozilla/5.0 (Linux; Android 9) Mobile Safari/537.36'
            }
        });

        const $ = cheerio.load(response.data);
        const pages = [];
        $('option').each((index, element) => {
            pages.push($(element).attr('value'));
        });

        // 获取所有章节
        const chapters = [];
        for (const page of pages) {
            const pageResponse = await axios.get(BASE_URL + page, {
                headers: {
                    'User-Agent': 'Mozilla/5.0 (Linux; Android 9) Mobile Safari/537.36'
                }
            });
            const page$ = cheerio.load(pageResponse.data);
            
            // 假设第二个 section-list 包含章节
            const sectionLists = page$('.section-list');
            if (sectionLists.length > 1) {
                sectionLists.eq(1).find('a').each((index, element) => {
                    let chapterUrl = page$(element).attr('href');
                    if (!chapterUrl) {
                        // 处理特殊URL情况
                        chapterUrl = `data:;base64,${Buffer.from(`#next_url@href|${index < sectionLists.length - 1 ? page$(sectionLists.get(index + 1)).find('a').attr('href') : page$(sectionLists.get(index - 1)).find('a').attr('href')}`).toString('base64')},{"type": "chapter"}`;
                    } else if (!chapterUrl.startsWith('http')) {
                        chapterUrl = BASE_URL + chapterUrl;
                    }
                    
                    chapters.push({
                        name: page$(element).text().trim(),
                        url: chapterUrl
                    });
                });
            }
        }

        res.json(chapters);
    } catch (error) {
        console.error('TOC error:', error);
        res.status(500).json({ error: 'Internal server error' });
    }
});

// 获取章节内容
router.get('/content', async (req, res) => {
    try {
        let { url } = req.query;
        if (!url) {
            return res.status(400).json({ error: 'Chapter URL is required' });
        }

        // 处理特殊编码的URL
        if (url.startsWith('data:;base64,')) {
            const decodedData = Buffer.from(url.split(',')[1].split(',')[0], 'base64').toString('utf-8');
            const [ruleStr, initialUrl] = decodedData.split('|');
            
            let finalUrl = initialUrl;
            let initialCount = 0;
            const finalCount = 10;
            
            while (initialCount < finalCount) {
                initialCount++;
                const response = await axios.get(BASE_URL + finalUrl, {
                    headers: {
                        'User-Agent': 'Mozilla/5.0 (Linux; Android 9) Mobile Safari/537.36'
                    }
                });
                
                const $ = cheerio.load(response.data);
                const thUrl = $(ruleStr).attr('href');
                finalUrl = thUrl;
                
                if (!thUrl || !thUrl.includes('_')) break;
            }
            
            url = BASE_URL + finalUrl;
        }

        // 获取章节内容
        const response = await axios.get(url, {
            headers: {
                'User-Agent': 'Mozilla/5.0 (Linux; Android 9) Mobile Safari/537.36'
            }
        });

        const $ = cheerio.load(response.data);
        let content = $('#content').html();
        
        // 清理内容
        content = content.replace(/<a[^>]*>.*?<\/a>/g, '');
        content = content.replace(/<script[^>]*>.*?<\/script>/g, '');
        content = content.replace(/<style[^>]*>.*?<\/style>/g, '');
        
        // 获取下一章URL
        let nextUrl = $('#next_url').attr('href');
        if (nextUrl && nextUrl.includes('_')) {
            nextUrl = BASE_URL + nextUrl;
        } else {
            nextUrl = '';
        }

        res.json({
            content: content,
            nextUrl: nextUrl
        });
    } catch (error) {
        console.error('Content error:', error);
        res.status(500).json({ error: 'Internal server error' });
    }
});

module.exports = router;